﻿using System;
using GeoAPI.Geometries;
using YJKGridTopologyCal.Index.Strtree;

namespace YJKGridTopologyCal.Operation.Distance
{
	public class IndexedFacetDistance
	{
		public static double Distance(IGeometry g1, IGeometry g2)
		{
			return new IndexedFacetDistance(g1).GetDistance(g2);
		}

		public IndexedFacetDistance(IGeometry g1)
		{
			this._cachedTree = FacetSequenceTreeBuilder.BuildSTRtree(g1);
		}

		public double GetDistance(IGeometry g)
		{
			STRtree<FacetSequence> tree = FacetSequenceTreeBuilder.BuildSTRtree(g);
			return IndexedFacetDistance.FacetDistance(this._cachedTree.NearestNeighbour(tree, new IndexedFacetDistance.FacetSequenceDistance()));
		}

		private static double FacetDistance(FacetSequence[] obj)
		{
			return obj[0].Distance(obj[1]);
		}

		private readonly STRtree<FacetSequence> _cachedTree;

		private class FacetSequenceDistance : IItemDistance<Envelope, FacetSequence>
		{
			public double Distance(IBoundable<Envelope, FacetSequence> item1, IBoundable<Envelope, FacetSequence> item2)
			{
				return item1.Item.Distance(item2.Item);
			}
		}
	}
}
